import { MongooseFactory } from './../kalend';

const WeChatTokenSchema = MongooseFactory.Schema({
     jsapi_ticket: String,
    cache_duration: Date,
    access_token:String
});

WeChatTokenSchema.statics = {
    /**
     * 
     * @param {*} cb 
     */
    getToken(cb:any) {
                this.find({}).sort({cache_duration:-1}).limit(1).exec(function (err:any, result:any) {
            if (err) throw err;
            return cb(result[0]);
        });
    },
    /**
     * 
     * @param {*} access_token 
     * @param {*} jsapi_ticket 
     * @param {*} cb 
     */
    setToken(jsapi_ticket:any,access_token:any, cache_duration:any, cb:any) {
        // 有则更新，无则添加
        var query = {
            jsapi_ticket: jsapi_ticket
        };
        var save = {
            jsapi_ticket: jsapi_ticket,
            cache_duration:cache_duration,
            access_token:access_token
        }
        var options = {
            upsert: true
        };
        this.update(query, save, options, function (err:any, result:any) {
            if (err) throw err;
            return cb(null);
        });
    }

}

export const weChatTokenSchema = MongooseFactory.Model("WeChatToken", WeChatTokenSchema);
